
/**
 *	frontend social login module
 *	gigya (gigya.com) based frontend module that enables a user to login with one of his/her social accounts
 *	facebook / twitter / google / yahoo ..
 *
 * 	the class is documented in the file itself. if you find any bugs help us out and report them. 
 * 	if you report a bug, make sure you give us enough information (include your code).
 *
 *	@copyright		oneDot only <we@onedotonly.be>
 * 	@copyright		Copyright (c) 2010, oneDot only. All rights reserved.
 * 	@license		BSD License
 *
 *	@author			pieter van peteghem <pieter@onedotonly.be>
 */


add_header_element( "script", { "type":"text/javascript", "src":"http://cdn.gigya.com/JS/gigya.js?services=socialize" });

var SocialGigya = function ( vars ) {

	Object.extend( obj = $$( '.SocialGigya' ).pop().insert( new Element( "div", { id: vars.containerId })), SocialGigya_proto );
	obj.options = obj.extend_options( vars );
	
	return obj;
}


SocialGigya_proto = {

	// default options
	default_options	: {
	
	    showTermsLink: false,
	    showWhatsThis: false,
	    whatsThisText: false,	
	},
	
		
	// extend/overwrite default options with custom options
	extend_options	: function( vars ) {
	
		Object.extend( this.default_options, vars );		
		return this.default_options;
	},
	
	
	// logout function
	logout			: function() {
	
		gigya.services.socialize.logout({ APIKey: this.options.key }, { callback: this.userLogout.bind( this )});	
	},
	
	
	// login function & add user data
	login			: function() {
			
		var params = { 
		    showTermsLink: 'false',
		    width: this.options.width,
		    height: this.options.height,
		    redirectURL: this.options.redirectURL,
		    showTermsLink: false,
		    showWhatsThis: false,
		    whatsThisText: false,
		    containerID : this.options.containerId,
		    enabledProviders: this.options.opts,
		    lastLoginIndication: 'none'
		};
		
		gigya.services.socialize.showLoginUI({ APIKey: this.options.key }, params );
		gigya.services.socialize.getUserInfo({ APIKey: this.options.key }, { callback: this.userInfo.bind( this )});	
		gigya.services.socialize.getAlbums({ APIKey: this.options.key }, { callback: this.userAlbums.bind( this )});
	},
	
	
	userAlbums	: function( response ) {
		if( response.errorCode == 0 ) {
			var albums = response[ 'albums' ].asArray();
			if( null != albums && albums.length > 0 && $$( '.TextForm.facebook' )) {
			
				var form 	= $$( '.TextForm.facebook' ).pop();
				if( form ) {
					var select 	= form.select( '#source' ).pop();
			
					var useralbums = [];
					albums.each( function( album, index ) {
						useralbums[ index ] = { id: album.albumID, name: album.name };
						gigya.services.socialize.getPhotos({ APIKey: this.options.key }, { callback: this.userPhotos.bind( this ), albumIDs: album.albumID });
						select.insert( '<option value="' + album.albumID + '">facebook album - ' + album.name + '</option>', { position: 'top' } );
					}, this );
				}
				//console.log( useralbums );
			}
			else {
				
			}
		}
		else {
			
		}
	
	},
	
	
	userPhotos	: function( response ) {
		if( response.errorCode == 0 ) {
			var photos = response[ 'photos' ].asArray();
			if( null != photos && photos.length > 0 ) {
				//console.log( photos );
			}
			else {
				
			}
		}
		else {
			
		}
	
	},
	
	
	userInfo		: function( response ) {
	
		var passer	= true;
		var newbie	= {};
		
		switch( response.user.loginProvider ) {
		
			case 'facebook':
			
				newbie[ 'meta.fname' ]	= response.user.firstName;
				newbie[ 'meta.lname' ]	= response.user.lastName;
				newbie[ 'meta.email' ]	= response.user.email;
				newbie[ 'meta.mail' ]	= response.user.email;
				newbie[ 'meta.thumb' ]	= response.user.thumbnailURL;
				newbie[ 'meta.birthd' ]	= response.user.birthDay;
				newbie[ 'meta.birthm' ]	= response.user.birthMonth;
				newbie[ 'meta.birthy' ]	= response.user.birthYear;
				newbie[ 'user' ]		= response.user.email;
				newbie[ 'active' ]		= 1;
				newbie[ 'rank' ]		= 4;
				break;
		}
		
		xhttp.send( 
			'/xhttp.mod', 
			{ mod: "social.gigya", action: "setUser", vars: { user: newbie, gigyauid: response.user.UID }}, 
			this.pull_response.bind( this, response.user )
		);
	},
	
	
	addEmail		: function( response, user ) {
	
		if( $( 'gigya-missing-email').getValue()) {
			response.user.email = $( 'gigya-missing-email').getValue();
			if( this.validate( response.user.email )) {
				this.userInfo( response );
			}
		} else {
			$( 'gigya-info' ).update( 'no valid email' );			
		}
	},
	
	
	validate	: function( email ) {
	
		var regexp 	= new RegExp( "[\\w-.\\+]@[\\w-.]" );
		if( regexp.test( email ))
			return true;
		else 
			return false;
	},
	
	
	pull_response	: function( user, response ) {
	
		set = response.responseText.evalJSON();
		if( user.nickname ) {
			if( $( 'gigya-info' )) {
				$( 'gigya-info' ).update( 'logged in as ' + user.nickname + ' - <a href="#" id="logout">logout</span>' );
			} else {
				$( this.options.containerId ).up(0).insert( new Element( "span", { id: 'gigya-info' }).update( 'logged in as ' + user.nickname + ' - <a href="#" id="logout">logout</span>' ));
			}
			init.userid = set.userid;
		} else {
			if( $( 'gigya-info' )) {
				$( 'gigya-info' ).update( 'logged out' );
			} else {
				$( this.options.containerId ).up(0).insert( new Element( "span", { id: 'gigya-info' }).update( 'logged out' ));
			}
		}
		$( 'logout' ).observe( 'click', this.logout.bind( this ));
	},
	
	
	userLogout		: function( response ) {
	
		xhttp.send( 
			'/xhttp.mod', 
			{ mod: "social.gigya", action: "logout", vars: {}}, 
			this.responseLogout.bind( this, response.user )
		);
		
	},
	
	responseLogout	: function( user, response ) {

		var set = response.responseText.evalJSON();
		$( 'gigya-info' ).update( 'logged out' );

		window.location = set.redirectURL;	
		
	}
}